package org.springblade.common.config;

import me.chanjar.weixin.common.api.WxMessageInMemoryDuplicateChecker;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springblade.common.handle.SubscribeHandler;
import org.springblade.common.handle.UnsubscribeHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;


@Configuration
public class MainConfiguration {

	@Value("${weixin.appId}")
	private String appId;

	@Value("${weixin.appSecret}")
	private String appSecret;

	@Value("${weixin.aesKey}")
	private String aesKey;

	@Value("${weixin.token}")
	private String token;

	@Autowired
	private SubscribeHandler subscribeHandler;

	@Autowired
	private UnsubscribeHandler unsubscribeHandler;


	@Bean
	public WxMpConfigStorage wxMpConfigStorage() {
		WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
		configStorage.setAppId(this.appId);
		configStorage.setSecret(this.appSecret);
		configStorage.setAesKey(this.aesKey);
		configStorage.setToken(this.token);
		return configStorage;
	}

	@Bean
	public WxMpService wxMpService() {
		WxMpService wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(wxMpConfigStorage());
		return wxMpService;
	}

	@Bean
	public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
		WxMpMessageRouter router = new WxMpMessageRouter(wxMpService);
		// 消息去重
		router.setMessageDuplicateChecker(new WxMessageInMemoryDuplicateChecker());

		// 关注事件
		router.rule().async(false).msgType(EVENT).event(SUBSCRIBE)
			.handler(this.subscribeHandler)
			.end();

		// 取消关注事件
		router.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE)
			.handler(this.unsubscribeHandler)
			.end();
		return router;

	}


}
